package com.yvtian.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yvtian.admin.pojo.SysCode;
import com.yvtian.admin.dao.SysCodeMapper;
import com.yvtian.admin.service.SysCodeService;
import com.yvtian.utils.StringHelper;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * (sys_code)表服务实现类
 *
 * @author long
 * @since 2024-04-11 11:36:00
 */
@Service("sysCodeService")
public class SysCodeServiceImpl extends ServiceImpl<SysCodeMapper, SysCode> implements SysCodeService {

    @Override
    public IPage<SysCode> findByPage(Page<SysCode> page, SysCode sysCode) {
        LambdaQueryWrapper<SysCode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCode::getIsDel,0);
        if (StringHelper.isNotEmpty(sysCode.getCodeName())){
            queryWrapper.like(SysCode::getCodeName,sysCode.getCodeName());
        }
        if (StringHelper.isNotEmpty(sysCode.getTableName())){
            queryWrapper.like(SysCode::getTableName,sysCode.getTableName());
        }
        if (StringHelper.isNotEmpty(sysCode.getRemark())){
            queryWrapper.like(SysCode::getRemark,sysCode.getRemark());
        }
        return this.page(page, queryWrapper);
    }

    @Override
    public synchronized String getCode(String tableName) {
        LambdaQueryWrapper<SysCode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCode::getIsDel,0);
        queryWrapper.eq(SysCode::getTableName,tableName);
        SysCode sysCode = this.getOne(queryWrapper);
        if (sysCode == null){
            throw new RuntimeException("编码未定义");
        }else {
            LambdaUpdateWrapper<SysCode> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysCode::getId,sysCode.getId());
            updateWrapper.set(SysCode::getCurrNum,sysCode.getCurrNum() + 1);
            this.update(updateWrapper);
        }
        String codeName = sysCode.getCodeName();
        String codeFormat = sysCode.getCodeFormat();
        int currNum = sysCode.getCurrNum() + 1;
        String separatorStr = sysCode.getSeparatorStr();

        SimpleDateFormat dateFormat = new SimpleDateFormat(codeFormat);
        String format = dateFormat.format(new Date());

        return codeName + format + separatorStr + currNum;

    }
}

